import { loanBook,loanReader } from "../../apis/gyt"
import {getBarcode} from "../../utils/block"
var nfc=require("../../utils/nfc");
var _that;
Page({
  data: {switchModeValue:true,
    reader:{},
    rdid:"", 
    bookId: '' ,
    islibreader:false,
    result:[]
  },
  async nfcRead(uid){
    await nfc.connect();
    var block=await nfc.getBlock(0,3);
    if(block[1]==0){
      wx.showToast({title: '未加工标签',icon:"error"})
      return;
    }
    var barcode=getBarcode(block);
    
    var res=await _that.loanBook(_that.data.rdid,barcode,uid);
    if(res.right){
      await nfc.setAfi(0xC2);
    }
    
  },switchMode(){
    var flag=this.data.switchModeValue;
    this.setData({switchModeValue:!flag})
  },
  onLoad(option){
    var reader=wx.getStorageSync('curreader');
    var libcode=wx.getStorageSync('libcode');
    this.setData({islibreader:libcode!=reader.rdLib});
    this.setData({reader:reader,rdid:reader.rdid});
    _that=this;
    nfc.start();
    nfc.onread(this.nfcRead);
  },
  onUnload(){
    nfc.unread();
    nfc.close();
    nfc.stop();
  },
  async loanBook(rdid,barcode,uid){
    var res=await loanBook(rdid,barcode,uid);
    var result=this.data.result;
    if(!res.biblio){
      return wx.showToast({title: '没有图书条码：'+ barcode})
    }
    for(var ms of res.msList){
      ms.message=ms.message.split("<",2)[0];
    }
    result.push(res);
    this.setData({result:result});
    if(res.right){
     var rd= await loanReader(rdid);
     this.setData({reader:rd.reader});
    }
    return res;
  },
  scanBarcode() {
    wx.scanCode({
      success: (res) => this.loanBook(this.data.rdid,res.result)
    })
  },
  
  inputBookId(e) { 
    this.setData({ bookId: e.detail.value });
 },
  
  goToConfirm() {
    this.loanBook(this.data.rdid,this.data.bookId);
  },
  navigateRenew(){
    var reader=wx.getStorageSync('curreader');
    wx.navigateTo({
      url: `/pages/renew/renew?rdid=${reader.rdid}`
    })
  },
})